const express = require("express");
const { send } = require("express/lib/response");
// 创建路由器对象
const c = express.Router();
// 引入jwt模块
const jwt = require("jsonwebtoken");
// 引入密钥 和 过期时间
const { secretKey, expiresIn } = require("../config/config");
// 引入第三方连接池模块
const pool = require("../pool/pool");
const Auth = require('../middlewares/Auth')
//****************************** */
//1.测试token
c.get("/product", (req, res, next) => {
  const token = (req.headers.authorization || "").slice(7);
  if(Auth.verifyToken(token)){
    res.send({"code":"200","msg":"token有效"})
  }else{
    res.send({"code":401,"msg":"token无效重新登录"})
  }
});

  // 2.车辆数据获取接口
  c.get('/cardata:page?',(req,res,next)=>{
    // console.log(req.query)
    let obj = req.query
    let sql = `SELECT * FROM car   LIMIT ${(obj.page - 1) * 3},3`
    // console.log(obj.carname);
    // console.log(sql)
    pool.query(sql,(err,data)=>{
      if(err){next(err);return;}
      // console.log(data.length)
      if(data.length!=0){
        res.send({"code":200,"data":data,"carCount":data.length})
      }else{
        res.send({"code":201,"msg":"暂无查询结果"})
      }
    })
  })

  // 3.获取车辆类型信息
  c.get('/cartype',(req,res,next)=>{
    let sql = 'SELECT * FROM car_type'
    pool.query(sql,(err,data)=>{
      if(err){next(err);return;}
      // console.log(data)
      res.send({"data":data})
    })
  })
  // 4.查询热销车辆
  c.get('/ishot',(req,res,next)=>{
    let sql = `SELECT * FROM car WHERE car_ishot=1`
    pool.query(sql,(err,data)=>{
      if(err){next(err);return;}
      res.send({"data":data,"carCount":data.length})
    })
  })
  // 5.搜索车辆操作
  c.get('/searchcar:carname?',(req,res,next)=>{
    let obj = req.query
    // console.log(obj.carname)
    let sql = `SELECT * FROM car WHERE car_name LIKE '%${obj.carname}%'`
    // console.log(sql)
    pool.query(sql,(err,data)=>{
      if(err){next(err);return;}
      if(data.length!=0){
        res.send({"code":200,"data":data,"carCount":data.length})
      }else{
        res.send({"code":201,"msg":"暂无查询结果","data":data,"carCount":data.length})
      }
    })
  })
  // 6.查询具体车辆信息
  c.get('/detailcar:id?',(req,res,next)=>{
    let obj = req.query
    console.log(obj)
    sql = `SELECT * FROM car WHERE car_id =?`
    pool.query(sql,obj.id,(err,data)=>{
      if(err){next(err);return;}
      // console.log(data)
      res.send({"code":200,"data":data})
    })
  })
  // 7.首页加载车辆信息数据
  c.post('/getdatacar',(req,res,next)=>{
    let obj = req.body
    // console.log(obj)
    let sql =  'select * from car where car_type_id = ? limit 0,4 '
    pool.query(sql,[obj.Cid],(err,data)=>{
      if(err){next(err);return}
      // console.log(data)
      if(data.length!==0){
        res.send({"code":200,"data":data})
      }
    })
  })
//*************************//
module.exports = c;
